let methods = {
  strFormat() {
    this.inputStr = strFormat(this.inputStr)
    this.updateLineNumbers()
  },
  handleButtonClick(func, copyOutputStr) {
    try {
      func(this);
      if (copyOutputStr && this.checkPassFlag) this.copyTextIn(this.outputStr)
      this.checkPassFlag = true
    } catch (e) {
      this.$message.error("操作失败：" + e.message);
    }
  },
  validateInput() {
    if (this.inputStr === "") {
      this.$message.warning("请输入数据");
      this.checkPassFlag = false
      return false;
    }
    return true;
  },
  validateOutput() {
    if (this.outputStr === "") {
      this.$message.warning("请输入结果数据");
      this.checkPassFlag = false
      return false;
    }
    return true;
  },
  copyInput() {
    if (this.inputType === 'obj') {
      this.copyTextIn(jsonToStrFormat(this.inputObj))
    } else {
      this.copyTextIn(this.inputStr)
    }
  },
  copyTextIn(content) {
    copyTextIn(content)
    this.$message.success('复制 ' + content + ' 成功。')
  },
  // 更新输入框行号
  updateLineNumbers() {
    if (this.inputType === 'obj' || this.inputStr === "" || !this.inputStr) {
      return
    }
    this.lines = this.inputStr.split('\n').length;
    this.$refs.lineNumbers.innerHTML = Array.from({length: this.lines}, (_, i) => i + 1).join('<br>');
  },
  // 更新输出框行号
  updateLineNumbersOut() {
    if (!this.outputStr || this.outputStr === "") {
      return
    }
    this.linesOut = this.outputStr.split('\n').length;
    this.$refs.lineNumbersOut.innerHTML = Array.from({length: this.linesOut}, (_, i) => i + 1).join('<br>');
  },
  dataChange() {
    if (this.inputType === 'obj') {
      this.inputStr = jsonToStrFormat(this.inputObj)
      this.inputType = 'str'
      setTimeout(() => this.updateLineNumbers(), 100);
    } else {
      this.inputObj = strToJson(this.inputStr)
      this.inputType = 'obj'
    }
    this.childrenJsonDisplay = true
  },
  dataChangeOnly() {
    if (this.inputType === 'obj') {
      this.inputStr = jsonToStrFormat(this.inputObj)
    } else {
      this.inputObj = strToJson(this.inputStr)
    }
  },
  rightDisplay() {
    this.displayRight = !this.displayRight;
    if (this.displayRight) {
      this.rightClass = 'right'
      this.leftClass = 'left'
      this.inputClass = 'input'
    } else {
      this.rightClass = 'right-hide'
      this.leftClass = 'left left-all'
      this.inputClass = 'input input-left-all'
    }
  },
  // 输入输出数据创建或修改， dataObj 为数据对象，data输入str
  inputCreateOrUpdate: function (dataObj, data) {
    let addFlag = true
    for (const item of this.saveData) {
      if (item.name === dataObj.name) {
        dataObj = item
        dataObj.data = data
        addFlag = false
        break
      }
    }

    console.log('addFlag', addFlag, jsonToStrFormat(dataObj))
    if (addFlag) {
      this.saveData.push(dataObj)
      // 示例：使用 `writeData` 函数写入数据
      writeData(dataObj);
    } else {
      // 示例：使用 `updateData` 函数更新数据
      updateData(cloneObj(dataObj));
    }
  },
  saveDataDo() {
    let data = this.inputStr
    // 前置判断
    if (this.inputType === 'obj') {
      data = jsonToStrFormat(this.inputObj)
    }
    if (data === "" || data === null) {
      this.$message.warning("请输入数据");
      return;
    }
    if (this.jsonName === "") {
      this.$message.warning("请输入文件名");
      return;
    }

    let dataObj = {
      name: this.jsonName,
      data: data,
      outData: this.outputStr
    }
    this.inputCreateOrUpdate(dataObj, data);

    this.jsonName = ''
    this.$message.success("保存成功")
    this.jsonNameDialog = false
  },
  thisDataChange() {
    if (this.inputType === 'obj') {
      if (strIsJson(this.thisDataObj.data)) {
        this.inputObj = strToJson(this.thisDataObj.data)
      } else {
        this.inputType = 'str'
        this.inputStr = this.thisDataObj.data
      }
    } else {
      this.inputStr = this.thisDataObj.data
    }
  },
  caseChange() {
    if (this.inputType === 'obj') {
      if (strIsObjOrArray(this.caseObj.inputData)) {
        this.inputObj = strToJson(this.caseObj.inputData)
      } else {
        this.inputType = 'str'
        this.inputStr = this.caseObj.inputData
      }
    } else {
      this.inputStr = this.caseObj.inputData
    }
    // 延时50ms
    setTimeout(() => {
      this.updateLineNumbers()
      setTimeout(() => {
        this.outputStr = this.caseObj.outputData
      }, 30)
    }, 30);
  },
  // vue2 输入对象更新，用于vue2 bug临时方案
  inoutObjReference() {
    this.inputObj = {}
    this.inputObj = strToJson(this.inputStr)
  },
  getArr(strOrArr) {
    if (typeof strOrArr === "string") {
      if (this.inputStr === "") {
        this.$message.error("请输入数据");
        return;
      }
      return strOrArr.replaceAll(/"/g, '')
        .split("\n").map(item => item.trim()).filter(item => item !== "");
    } else {
      return strOrArr
    }
  },
  setJsonDisplay() {
    this.childrenJsonDisplay = !this.childrenJsonDisplay
    this.$refs.child.setJsonDisplay(this.childrenJsonDisplay)
  },
  importConfigData() {
    this.uploadBtnConfigFlag = true
  },
  importData() {
    this.uploadFlag = true
  },
  uploadChange(file, fileList) {
    this.uploadData = fileList;
  },
  uploadInputOutput() {
    if (this.uploadData.length === 0) {
      this.$message.warning('请选择要上传的文件');
      return;
    }

    const file = this.uploadData[0].raw; // 获取第一个文件
    const reader = new FileReader();

    reader.onload = (event) => {
      try {
        const jsonData = JSON.parse(event.target.result);
        if (Array.isArray(jsonData)) {
          for (const item of jsonData) {
            if (typeof item === 'object' && item !== null && item.name && item.data) {
              this.inputCreateOrUpdate(item, item.data);
            }
          }
        }
        this.uploadFlag = false;
        this.$message.success('导入数据成功');
      } catch (error) {
        this.$message.error('文件解析失败，请确保文件是有效的JSON格式');
        console.error('File parsing error:', error);
      }
    };

    reader.readAsText(file);
  },
  uploadBtnConfig() {
    if (this.uploadData.length === 0) {
      this.$message.warning('请选择要上传的文件');
      return;
    }

    const file = this.uploadData[0].raw; // 获取第一个文件
    const reader = new FileReader();

    reader.onload = (event) => {
      try {
        const jsonData = JSON.parse(event.target.result);
        if (Array.isArray(jsonData)) {
          this.updateActionArr = jsonData
          this.updateAction2ActionArr(jsonData)
          writeConfigData(this.updateActionArr)
        }
        this.$message.success('导入数据成功');
      } catch (error) {
        this.$message.error('文件解析失败，请确保文件是有效的JSON格式');
        console.error('File parsing error:', error);
      }
    };
    this.uploadBtnConfigFlag = false;
    reader.readAsText(file);
  },
  handleExceed(files, fileList) {
    this.$message.warning(`当前限制选择 ${this.$refs.uploadInputOutputRef.limit} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
  },
  // 下拉菜单处理
  dropdownHandel(command) {
    switch (command) {
      case 'settingBtn':
        this.btnSettingStart();
        break;
      case 'exportConfigData':
        this.exportConfigData()
        break;
      case 'importConfigData1':
        this.importConfigData()
        break;
    }
  },
  actionData2UpdateArrTree: function () {
    let id = 0
    let row = 0
    for (const key in this.actionData) {
      // 1.遍历行
      let obj = {
        id: id++,
        label: `第${++row}行`,
        // 行无操作
        type: 'row',
        data: {},
        display: true,
        children: []
      }
      this.updateActionArr.push(obj)

      // 2.遍历分组
      for (const key2 in this.actionData[key]) {
        // 2.1.处理分组属性
        let classArr = this.actionData[key][key2]
        let label = classArr.name
        if (!(label && label.trim !== "")) {
          label = '无分组名称'
        }
        let classStr = classArr.class
        if (classStr && classStr.trim !== "") {
          classStr = classStr.trim().replaceAll('\n', '')
        } else {
          classStr = 'light-blue-green'
        }

        // 2.2.增加分组对象
        let obj2 = {
          id: id++,
          label: label,
          // 分组
          type: 'class',
          data: {},
          class: classStr,
          display: true,
          children: []
        }
        obj.children.push(obj2)

        for (const actObj of classArr.arr) {
          // 3.1.处理按钮属性
          let actObjClone = cloneObj(actObj)
          actObjClone.fun = this.fun2String(actObj.fun)

          // 3.2.增加对象按钮
          let obj3 = {
            id: id++,
            label: actObj.txt,
            // 按钮
            type: 'btn',
            data: actObjClone,
            btnCls: actObj.type,
            display: true,
          }
          obj2.children.push(obj3)
        }
      }
    }
  },
  // 页面按钮设置开始 ----
  btnSettingStart: function () {
    if (!this.updateActionArr || this.updateActionArr.length === 0) {
      this.actionData2UpdateArrTree();
    }
    this.updateFlag = true
  },
  // 修改按钮对象 转 显示按钮对象
  updateAction2ActionArr: function (arrInd) {
    this.hideBtnArr = []
    const actionData = [];
    // 循环行对象
    for (const row of arrInd) {
      if (row.type !== 'row') continue;
      let rowDisplay = row.display;

      const rowData = [];
      const rowDataHide = [];
      // 循环分组对象
      for (const cls of row.children) {
        if (cls.type !== 'class') continue;

        const className = cls.label === '无分组名称' ? '' : cls.label;
        const classClass = cls.class || '';

        const arr = [];
        const arrHide = [];
        const classObj = {
          name: `${className}`,
          class: classClass,
          arr: arr
        }
        const classObjHide = {
          name: `${className}`,
          class: classClass,
          arr: arrHide
        }
        // 循环按钮对象
        for (const btn of cls.children) {
          if (btn.type !== 'btn') continue;
          let btnDisplay = btn.display;
          let actionObj = cloneObj(btn.data);
          actionObj.fun = this.funStr2Object(actionObj.fun)
          actionObj.type = btn.btnCls;
          actionObj.txt = btn.label;
          if (!cls.display ||!btnDisplay) {
            arrHide.push(actionObj);
          } else {
            arr.push(actionObj);
          }
        }

        if (arr.length > 0) {
          rowData.push(classObj);
        }
        rowDataHide.push(classObjHide);
      }
      if (rowDisplay) {
        actionData.push(rowData)
        if (rowDataHide.length > 0) {
          for (const rowDataHideElement of rowDataHide) {
            if (rowDataHideElement.arr.length > 0) {
              this.hideBtnArr.push(rowDataHideElement)
            }
          }
        }
      } else {
        for (const rowDatum of rowData) {
          this.hideBtnArr.push(rowDatum)
        }
      }
    }
    this.actionData = actionData;
    return actionData;
  },
  updateDo() {
    this.actionData = this.updateAction2ActionArr(this.updateActionArr);
    writeConfigData(this.updateActionArr)
    this.updateFlag = false
  },
  filterActionNode(value, data) {
    if (!value || value === '') return true;
    return data.label.indexOf(value) !== -1;
  },
  // 树结构是否能拖拽
  updateAllowDrop(draggingNode, dropNode, type) {
    console.log('tree drag enter: ', dropNode.data.type, draggingNode.data.type, type);
    if (type === 'inner') {
      return (draggingNode.data.type === 'btn' && dropNode.data.type === 'class') ||
        (draggingNode.data.type === 'class' && dropNode.data.type === 'row');
    } else {
      return draggingNode.data.type === dropNode.data.type;
    }
  },
  deleteData() {
    if (this.saveData.includes(this.thisDataObj)) {
      this.saveData.splice(this.saveData.indexOf(this.thisDataObj), 1)

      let data = this.saveData
      this.saveData = []
      this.saveData = data
      deleteData(this.thisDataObj.name)
      this.thisDataObj = {}
      this.$message.success("删除成功", 800)
    }
  },
  // 函数、字符串转换
  fun2String(funIn) {
    // Convert the object to a string, serializing the function as a string
    if (typeof funIn === 'function') {
      let result = funIn.toString();
      return result.substring(result.indexOf('{') + 1, result.lastIndexOf('}'));
    } else if (funIn) {
      return funIn.toString();
    } else {
      return ''
    }
  },
  funStr2Object(strIn) {
    if (typeof strIn === 'string' && strIn !== '') {
      return new Function('that', strIn)
    }
    console.warn('不是字符串或为空字符串')
  },
  btnUpdateStart(data) {
    this.btnUpdateDataBk = data
    if (data.type === 'btn') {
      this.btnUpdateTitle = '修改按钮'
    } else if (data.type === 'class') {
      this.btnUpdateTitle = '修改分组'
    }
    this.btnUpdateData = {...data}
    this.btnAddFlag = false
    this.btnUpdateFlag = true
  },
  btnUpdateDo() {
    if (this.btnAddFlag) {
      this.btnUpdateDataBk.children.push(this.btnUpdateData)
    } else {
      for (const key in this.btnUpdateData) {
        this.btnUpdateDataBk[key] = this.btnUpdateData[key]
      }
    }
    this.btnUpdateFlag = false
  },
  btnAddStart(data) {
    this.btnUpdateDataBk = data
    this.btnUpdateData = {...this.btnObjAddDemo}
    if (data.type === 'row') {
      this.btnUpdateTitle = '增加分组'
      this.btnUpdateData.type = 'class'
      this.btnUpdateData.children = []
    } else if (data.type === 'class') {
      this.btnUpdateTitle = '增加按钮'
      this.btnUpdateData.type = 'btn'
      this.btnUpdateData.data = {
        "txt": "",
        "fun": "",
        "desc": "",
        "type": "",
        "copyOutputStr": false
      }
    }
    this.btnAddFlag = true
    this.btnUpdateFlag = true
  },
  exportConfigData() {
    try {
      const jsonData = jsonToStr(this.updateActionArr);
      const blob = new Blob([jsonData], {type: "application/json;charset=utf-8;"});
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      const str = dataToStr(new Date()).replace(/[^0-9]/g, "");
      a.download = `页面按钮数据设置_${str}.json`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
      console.log("Data exported to file.");
    } catch (error) {
      console.error("Error exporting data:", error);
    }
  },
  getStrRow(str) {
    if (str) {
      return str.length - str.replaceAll('\n', '').length + 1
    } else {
      return 2
    }
  },
  // 处理折叠
  collapseHandleChange() {

  }
}
